﻿using ZX.SYS.Library;
using ZX.BLL.Extend;
using ZX.DBModule;
using System.IO;
using ZX.Common;
using ZX.SYS.Library;
using System.Data;
using ZX.DAL.DBExtend;
using System.Text;
using System.IO;
using System.Net;
using System.Web;
using System.Configuration;
using System.Data.SqlClient;
using System.Xml;
using System.Net.NetworkInformation;
using ZX.Common;
using System;
using OpenExpressApp.MetaModel.Utils;
namespace ZX.SYS.Bussiness
{
    //消息出口
    public  class MQOut : BLL.Extend.BaseBussnies
    {
        public static readonly string decount = ConfigurationManager.AppSettings["DeCount"].ToString();
        public static readonly string spwd = ConfigurationManager.AppSettings["SPWD"].ToString();
        public static readonly string URL = ConfigurationManager.AppSettings["MURL"].ToString();
        public static readonly string AllURL = "http://" + URL.Split(';')[0] + "/" + URL.Split(';')[1];
        private readonly static int TIMEOUT = 15000;




        private CookieContainer _cookieCon = new CookieContainer();
        private CredentialCache _credentials;
        /// <summary>
        /// 判断能否链接到服务器
        /// </summary>
        /// <returns></returns>
        private bool IsConnNet()
        {
            PingReply pr = (new Ping()).Send(URL.Split(';')[0]);
            if (pr.Status == IPStatus.Success)
                return true;
            else
                return false;
        }

        //账号信息
        public DataTable Account()
        {
            if (ZX.Common.WebCache.Get("AcData") != null)
            {
                return ZX.Common.WebCache.Get("AcData") as DataTable;
            }
            else
            {
                string sql = @"SELECT [MQAID]
                              ,[MQtype]
                              ,[Aname]
                              ,[Aobject]
                              ,[Acount]
                              ,[Apwd]
                              ,[IsValue]
                          FROM [MQAccount] where IsValue=1";
                DataTable dt = (new DbSql()).ExecuteQuery(sql);
                ZX.Common.WebCache.Insert("AcData", dt);
                return dt;
            }

        }

        //系统短信发送
        public string SystemSend(string meg, string phones, string pwd)
        {
            if (pwd == spwd)
            {
                return sendmessage(phones,meg);
            }
            else
                return "验证码错误！";
        
        }

        /// <summary>
        /// 发送短信
        /// </summary>
        /// <param name="phone">手机号码</param>
        /// <param name="msg">短信内容</param>
        /// <returns></returns>
        public string sendmessage(string phone, string msg)
        {
            if (!IsConnNet())
                return "没有可用的网络！";
            DataRow[] dr;
            if(HttpContext.Current==null)
                dr = Account().Select("Aobject = '" + decount + "'");//默认使用账号
            else
                dr = Account().Select("Aobject like '%" + HttpContext.Current.User.Identity.Name + "%'");

            if (dr != null)
            {
                string Msg = System.Web.HttpUtility.UrlEncode(msg, System.Text.Encoding.UTF8);
                return GetPageContent(AllURL + "?username=" + dr[0]["Acount"].ToString().Split(';')[0] + "&password=" + dr[0]["Apwd"].ToString() + "&mobile=" + phone
                    + "&content=" + Msg + "&Extcode=" + dr[0]["Acount"].ToString().Split(';')[1] + "&senddate=", string.Empty);
            }
            else
                return "没有可用的账号";

       }

        /// <summary>
        /// 通过url请求数据
        /// </summary>
        /// <param name="url">被请求页面的url</param>
        /// <param name="proxyServer">代理服务器</param>
        /// <returns>返回页面内容</returns>
        public string GetPageContent(string url, string proxyServer)
        {
            StringBuilder ret = new StringBuilder("");
            HttpWebResponse rsp = null;

            try
            {
                Uri uri = new Uri(url);
                HttpWebRequest req = (HttpWebRequest)WebRequest.Create(uri);
                if (!string.IsNullOrEmpty(proxyServer))
                {
                    req.Proxy = new WebProxy(proxyServer);
                }
                req.CookieContainer = this._cookieCon;
                req.Headers.Add("Accept-Language: zh-cn");
                req.AllowAutoRedirect = true;
                req.Timeout = TIMEOUT;

                if (this._credentials != null)
                {
                    req.PreAuthenticate = true;
                    req.Credentials = this._credentials;
                }
                rsp = (HttpWebResponse)req.GetResponse();

                Stream rspStream = rsp.GetResponseStream();
                StreamReader sr = new StreamReader(rspStream, System.Text.Encoding.UTF8);

                //获取数据
                Char[] read = new Char[256];
                int count = sr.Read(read, 0, 256);
                while (count > 0)
                {
                    ret.Append(read, 0, count);
                    count = sr.Read(read, 0, 256);
                }
            }
            catch (Exception e)
            {
                ret.Append(e.Message);
            }
            finally
            {
                if (rsp != null)
                {
                    rsp.Close();
                }
            }
            return ret.ToString();
        }

        //敏感词过滤
        public string CheckSms(string phones, string cont)
        {
            String uname = System.Configuration.ConfigurationManager.AppSettings["SmsUname"];
            String upass = System.Configuration.ConfigurationManager.AppSettings["SmsUpass"];
            String extcode = System.Configuration.ConfigurationManager.AppSettings["SmsExtcode"];
            String checkUrl = System.Configuration.ConfigurationManager.AppSettings["smsGlUrl"];
            StringBuilder sbc = new StringBuilder();
            sbc.AppendFormat(checkUrl+"msg={0}",HttpUtility.UrlEncode(cont,Encoding.GetEncoding("utf-8")));
            string check = GetPageContent(sbc.ToString(), string.Empty);
            if (check == "" || check==string.Empty)
            {
                StringBuilder sb = new StringBuilder();
                sb.AppendFormat("username={0}&", uname);//用户名
                sb.AppendFormat("password={0}&", upass);//密码
                sb.AppendFormat("content={0}&", cont);//短信内容
                sb.AppendFormat("mobile={0}&", phones);//手机号,多个以分号分隔
                sb.AppendFormat("extcode={0}&", extcode);//扩展号，如果需要短信报告以及回复功能必须填写此项
                sb.AppendFormat("senddate={0}", "");//预约时间，如果为空代表即时发送
                return SendSMS(sb.ToString());
            }
            else
            {
                return "发现敏感词："+check;
            }
        }

        /// <summary>
        /// 以POST方式提交数据
        /// </summary>
        /// <param name="postData"></param>
        /// <returns></returns>
        public String SendSMS(String postData)
        {
            //获取配置文件中的URL并构建一个URL对象
            String url = System.Configuration.ConfigurationManager.AppSettings["smsUrl"];
            Uri uri = new Uri(url);

            Encoding encoding = Encoding.GetEncoding("utf-8");
            byte[] bytesToPost = encoding.GetBytes(postData);

            HttpWebRequest wr = (HttpWebRequest)HttpWebRequest.Create(uri);
            wr.UserAgent = "Mozilla/4.0 (compatible; MSIE 7.0; Windows NT 5.2; .NET CLR 1.1.4322; .NET CLR 2.0.50727)";
            wr.ContentType = "application/x-www-form-urlencoded";
            wr.Method = "POST";//如果此处为GET，长度会受限制
            wr.ContentLength = bytesToPost.Length;

            String stringResponse = String.Empty;//返回内容
            using (System.IO.Stream requestStream = wr.GetRequestStream())
            {
                requestStream.Write(bytesToPost, 0, bytesToPost.Length);
                using (Stream responseStream = wr.GetResponse().GetResponseStream())
                {
                    using (StreamReader responseReader = new StreamReader(responseStream, Encoding.UTF8))
                    {
                        stringResponse = responseReader.ReadToEnd();
                    }
                }
            }
            return stringResponse;
        }


    }

}
